package org.linlinjava.litemall.db.service;

import com.github.pagehelper.PageHelper;
import org.linlinjava.litemall.db.dao.LitemallCartMapper;
import org.linlinjava.litemall.db.domain.LitemallCart;
import org.linlinjava.litemall.db.domain.LitemallCartExample;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

@Service
public class LitemallCartService {
    @Resource
    private LitemallCartMapper cartMapper;

    /**
     * 查询购物车中是否存在某商品
     * 
     * @param goodsId 商品ID
     * @param productId 产品ID
     * @param userId 用户ID
     * @return 购物车项
     */
    public LitemallCart queryExist(Integer goodsId, Integer productId, Integer userId) {
        LitemallCartExample example = new LitemallCartExample();
        example.or().andGoodsIdEqualTo(goodsId).andProductIdEqualTo(productId).andUserIdEqualTo(userId).andDeletedEqualTo(false);
        return cartMapper.selectOneByExample(example);
    }
    
    /**
     * 查询购物车中是否存在某商品（使用规格ID列表）
     * 
     * @param goodsId 商品ID
     * @param specificationIds 规格ID列表
     * @param userId 用户ID
     * @return 购物车项
     */
    public LitemallCart queryExist(Integer goodsId, List<Integer> specificationIds, Integer userId) {
        // 先查询该用户该商品的所有购物车项
        LitemallCartExample example = new LitemallCartExample();
        example.or().andGoodsIdEqualTo(goodsId).andUserIdEqualTo(userId).andDeletedEqualTo(false);
        List<LitemallCart> cartList = cartMapper.selectByExample(example);
        
        if (cartList == null || cartList.isEmpty()) {
            return null;
        }
        
        // 将规格ID列表转换为数组
        Integer[] specIds = specificationIds != null ? specificationIds.toArray(new Integer[0]) : new Integer[0];
        
        // 遍历购物车项，找到规格匹配的项
        for (LitemallCart cart : cartList) {
            // 如果购物车项的specificationIds字段不为空，直接比较
            if (cart.getSpecificationIds() != null && Arrays.equals(cart.getSpecificationIds(), specIds)) {
                return cart;
            }
        }
        
        return null;
    }

    /**
     * 查询购物车中是否存在某商品（使用规格JSON字符串）
     * 
     * @param goodsId 商品ID
     * @param specificationsJson 规格JSON字符串
     * @param userId 用户ID
     * @return 购物车项
     */
    public LitemallCart queryExist(Integer goodsId, String specificationsJson, Integer userId) {
        // 先查询该用户该商品的所有购物车项
        LitemallCartExample example = new LitemallCartExample();
        example.or().andGoodsIdEqualTo(goodsId).andUserIdEqualTo(userId).andDeletedEqualTo(false);
        List<LitemallCart> cartList = cartMapper.selectByExample(example);
        
        if (cartList == null || cartList.isEmpty()) {
            return null;
        }
        
        // 遍历购物车项，找到规格匹配的项
        for (LitemallCart cart : cartList) {
            // 将购物车中的规格信息转换为字符串进行比较
            String cartSpecStr = cart.getSpecifications() != null ? Arrays.toString(cart.getSpecifications()) : "";
            if (specificationsJson != null && specificationsJson.equals(cartSpecStr)) {
                return cart;
            }
        }
        
        return null;
    }

    public void add(LitemallCart cart) {
        cart.setAddTime(LocalDateTime.now());
        cart.setUpdateTime(LocalDateTime.now());
        cartMapper.insertSelective(cart);
    }

    public int updateById(LitemallCart cart) {
        cart.setUpdateTime(LocalDateTime.now());
        return cartMapper.updateByPrimaryKeySelective(cart);
    }

    public List<LitemallCart> queryByUid(int userId) {
        LitemallCartExample example = new LitemallCartExample();
        example.or().andUserIdEqualTo(userId).andDeletedEqualTo(false);
        return cartMapper.selectByExample(example);
    }


    public List<LitemallCart> queryByUidAndChecked(Integer userId) {
        LitemallCartExample example = new LitemallCartExample();
        example.or().andUserIdEqualTo(userId).andCheckedEqualTo(true).andDeletedEqualTo(false);
        return cartMapper.selectByExample(example);
    }

    public int delete(List<Integer> productIdList, int userId) {
        LitemallCartExample example = new LitemallCartExample();
        example.or().andUserIdEqualTo(userId).andProductIdIn(productIdList);
        return cartMapper.logicalDeleteByExample(example);
    }

    public LitemallCart findById(Integer id) {
        return cartMapper.selectByPrimaryKey(id);
    }

    public LitemallCart findById(Integer userId, Integer id) {
        LitemallCartExample example = new LitemallCartExample();
        example.or().andUserIdEqualTo(userId).andIdEqualTo(id).andDeletedEqualTo(false);
        return cartMapper.selectOneByExample(example);
    }

    /**
     * 更新购物车项的勾选状态
     * 
     * @param userId 用户ID
     * @param cartIds 购物车ID列表
     * @param checked 是否勾选
     * @return 更新的记录数
     */
    public int updateCheck(Integer userId, List<Integer> cartIds, Boolean checked) {
        LitemallCartExample example = new LitemallCartExample();
        example.or().andUserIdEqualTo(userId).andIdIn(cartIds).andDeletedEqualTo(false);
        LitemallCart cart = new LitemallCart();
        cart.setChecked(checked);
        cart.setUpdateTime(LocalDateTime.now());
        return cartMapper.updateByExampleSelective(cart, example);
    }

    public void clearGoods(Integer userId) {
        LitemallCartExample example = new LitemallCartExample();
        example.or().andUserIdEqualTo(userId).andCheckedEqualTo(true);
        LitemallCart cart = new LitemallCart();
        cart.setDeleted(true);
        cartMapper.updateByExampleSelective(cart, example);
    }

    public List<LitemallCart> querySelective(Integer userId, Integer goodsId, Integer page, Integer limit, String sort, String order) {
        LitemallCartExample example = new LitemallCartExample();
        LitemallCartExample.Criteria criteria = example.createCriteria();

        if (!StringUtils.isEmpty(userId)) {
            criteria.andUserIdEqualTo(userId);
        }
        if (!StringUtils.isEmpty(goodsId)) {
            criteria.andGoodsIdEqualTo(goodsId);
        }
        criteria.andDeletedEqualTo(false);

        if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(order)) {
            example.setOrderByClause(sort + " " + order);
        }

        PageHelper.startPage(page, limit);
        return cartMapper.selectByExample(example);
    }

    public void deleteById(Integer id) {
        cartMapper.logicalDeleteByPrimaryKey(id);
    }

    public boolean checkExist(Integer goodsId) {
        LitemallCartExample example = new LitemallCartExample();
        example.or().andGoodsIdEqualTo(goodsId).andCheckedEqualTo(true).andDeletedEqualTo(false);
        return cartMapper.countByExample(example) != 0;
    }

    public void updateProduct(Integer id, String goodsSn, String goodsName, BigDecimal price, String url) {
        LitemallCart cart = new LitemallCart();
        cart.setPrice(price);
        cart.setPicUrl(url);
        cart.setGoodsSn(goodsSn);
        cart.setGoodsName(goodsName);
        LitemallCartExample example = new LitemallCartExample();
        example.or().andProductIdEqualTo(id);
        cartMapper.updateByExampleSelective(cart, example);
    }

    /**
     * 根据购物车ID列表和用户ID删除购物车项
     * 
     * @param cartIds 购物车ID列表
     * @param userId 用户ID
     * @return 删除的记录数
     */
    public int deleteByIds(List<Integer> cartIds, int userId) {
        LitemallCartExample example = new LitemallCartExample();
        example.or().andUserIdEqualTo(userId).andIdIn(cartIds);
        return cartMapper.logicalDeleteByExample(example);
    }
}
